/**
 * 
 */
package net.m510.autosurfer.core.utils;

import java.net.URI;
import java.nio.charset.Charset;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.FormElement;
import org.jsoup.select.Elements;

/**
 * @author m.goto
 *
 */
public final class AnalyzeUtils {
//	private static final Logger log = Logger.getLogger(AnalyzeUtils.class.getName());
	
	public static final Elements getFormDataElements(FormElement form) {
		Elements elems = form.getElementsByTag("input");
		elems.addAll(form.getElementsByTag("select"));
		return elems;
	}
	
	public static final FormElement getFormElementByName(Document doc, String name) {
		if ( name == null ) throw new IllegalArgumentException("name must be not null");
		for (FormElement e : doc.getAllElements().forms()) {
			if ( name.equals(e.attr("name"))) return e;
		}
		return null;
	}
	public static final FormElement getFormElementById(Document doc, String id) {
		if ( id == null ) throw new IllegalArgumentException("id must be not null");
		for (FormElement e : doc.getAllElements().forms()) {
			if ( id.equals(e.attr("id"))) return e;
		}
		return null;
	}
	
	public static final String DEFAULT_FILENAME = "file.txt";
	public static final String createFileName(HttpResponse response) {
		String filename = null;
		Header h = response.getFirstHeader("Content-Disposition");
		if ( h != null ) {
			String[] str = h.getValue().split(";");
			for (String s : str) {
				if ( s.contains("filename") ) {
					filename = s.split("=")[1].replaceAll("\"", "");
					break;
				}
			}
		}
		return (filename == null ? DEFAULT_FILENAME : filename );
	}
	
	public static final String getCharset(HttpResponse resp,String defaultCharset) {
		Header h = resp.getFirstHeader("Content-Type");
		if ( h == null ) return defaultCharset;
		HeaderElement[] hes = h.getElements();
		if ( hes.length == 0 ) return defaultCharset;
		NameValuePair p = h.getElements()[0].getParameterByName("charset");
		if ( p == null ) return defaultCharset;
		return p.getValue();
	}
	
	public static final String getCharset(HttpEntity entity, String defaultCharset) {
		ContentType ct = ContentType.get(entity);
		if ( ct == null ) return defaultCharset;
//		log.fine("HttpEntity.getContentType : "+ct);
		Charset charset = ct.getCharset();
		if ( charset == null ) return defaultCharset;
//		log.fine("return charset :"+charset);
		return charset.toString();
	}
	
	public static final URI resolveURIByFormAction(HttpClientContext context,Element form) {
		String action = form.attr("action");
		HttpHost host = context.getTargetHost();
		URI uri = URI.create(host.toURI());
		uri = uri.resolve(action);
		return uri;
		
	}
	public static final URI resolveURIByPath(HttpClientContext context,String path) {
		HttpHost host = context.getTargetHost();
		URI uri = URI.create(host.toURI());
		uri = uri.resolve(path);
		return uri;
	}
	
//	/**
//	 * cookieを保存する
//	 * @param file 保存先のファイル
//	 * @param store 保存したいCookieStoreオブジェクト
//	 * @throws IOException
//	 */
//	public static void saveCookie(CookieStore store,File file) throws IOException {
//		FileOutputStream fos = new FileOutputStream(file);
//		ObjectOutputStream oos = new ObjectOutputStream(fos);
//		try {
//			oos.writeObject(store.getCookies());
//			LogUtil.log(Level.FINE,store.getCookies(),"saved cookies");
//		} finally {
//			oos.close();
//		}
//	}
//	/**
//	 * cookieをファイルから読み込む
//	 * 
//	 * @param file cookieを保存したファイル
//	 * @param store 読み出したいCookieStoreオブジェクト このインスタンスに読み込んだCookieがaddされます
//	 * @throws IOException
//	 * @throws ClassNotFoundException
//	 */
//	public static void loadCookie(File file,CookieStore store) throws IOException, ClassNotFoundException {
//		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
//		@SuppressWarnings("unchecked")
//		List<Cookie> cs = (List<Cookie>)ois.readObject();
//		LogUtil.log(Level.FINE,cs,"readed cookies");
//		
//		for ( Cookie c : cs ) {
//			store.addCookie(c);
//		}
//		ois.close();
//	}
//	
}
